//
// Created by sgyt on 2020/4/2.
// 互斥锁的时间值
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <errno.h>
#include <string.h>

int main(int argc,char *argv[])
{
    struct timespec timespec;
    struct tm *tmp;
    char buf[1024];
    int err;

    //初始化静态互斥锁
    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

    //锁住变量
    pthread_mutex_lock(&lock);
    printf("mutex i lock\n");

    //获取当前时间
    clock_gettime(CLOCK_REALTIME,&timespec);
    tmp = localtime(&timespec.tv_sec);
    strftime(buf, sizeof(buf),"%r",tmp);
    printf("current time is %s\n",buf);

    //上10s中的锁
    timespec.tv_sec +=  10;
    err = pthread_mutex_timedlock(&lock,&timespec);
    clock_gettime(CLOCK_REALTIME,&timespec);
    tmp = localtime(&timespec.tv_sec);
    strftime(buf,sizeof(buf),"%r",tmp);
    printf("current time is %s\n",buf);

    if(err == 0)
    {
        printf("mutex locked again\n");
    }else{
        printf("can't lock again:%s\n",strerror(err));
    }
    return 0;
}
